package com.doordu.soa.service.data;

import java.nio.charset.Charset;
import java.util.List;

import javax.servlet.MultipartConfigElement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import com.doordu.soa.service.web.auth.interceptor.TokenInterceptor;
import com.doordu.soa.service.web.converter.String2DateConverter;
import com.doordu.soa.service.web.converter.String2LocalDateConverter;
import com.doordu.soa.service.web.converter.String2LocalDateTimeConverter;
import com.doordu.soa.service.web.utils.DoorduRequestMappingHandlerMapping;
import com.google.common.collect.Lists;


/**
 * 用于加载额外的定义配置.
 * 
 * @author kyler.tang
 *
 */
@SpringBootApplication
@ComponentScan(basePackages={"com.doordu.soa.service.data,com.doordu.soa.service.web.auth"})
@Configuration
@ImportResource(value = { "classpath:application-beans.xml" })
@EnableCaching 
@EnableScheduling
@ImportAutoConfiguration({com.doordu.soa.service.web.CommWebConifg.class})
public class ConfigClass extends WebMvcConfigurationSupport {
	static Logger log = LoggerFactory.getLogger(ConfigClass.class);
    @Value("${executor.coresize}")
    private Integer coresize;
    @Value("${executor.maxsize}")
    private Integer maxsize;
    @Value("${executor.queuesize}")
    private Integer queuesize;
    @Value("${executor.keepalived}")
    private Integer keepAlived;

	public ConfigClass() {
		// JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";// json 日期格式

	}

	@Override
	protected void addFormatters(FormatterRegistry registry) {

		registry.addConverter(new String2DateConverter());// 添加 String - Date
															// 的参数转换器

        registry.addConverter(new String2LocalDateConverter());
		registry.addConverter(new String2LocalDateTimeConverter());

		super.addFormatters(registry);
	}

	@Override
	protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		StringHttpMessageConverter smc = new StringHttpMessageConverter(Charset.forName("UTF-8"));
		converters.add(smc);
		FastJsonHttpMessageConverter4 fjmc = new FastJsonHttpMessageConverter4();
		fjmc.setSupportedMediaTypes(
				Lists.newArrayList(MediaType.APPLICATION_JSON_UTF8, MediaType.TEXT_PLAIN, MediaType.ALL));

		fjmc.setDefaultCharset(Charset.forName("utf-8"));

		FastJsonConfig config = new FastJsonConfig();
		// config.setDateFormat("yyyy-MM-dd HH:mm:ss");
		config.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNullStringAsEmpty,
				SerializerFeature.WriteMapNullValue);// 默认时间转换格式
		fjmc.setFastJsonConfig(config);

		converters.add(fjmc);

		super.configureMessageConverters(converters);
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**").addResourceLocations("classpath:/webapp/");
		super.addResourceHandlers(registry);

    }

	@Override
	@Bean
	public RequestMappingHandlerMapping requestMappingHandlerMapping() {
		RequestMappingHandlerMapping handlerMapping = new DoorduRequestMappingHandlerMapping();
		handlerMapping.setOrder(0);
		handlerMapping.setInterceptors(getInterceptors());
		return handlerMapping;
	}

	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/**");
		//registry.addInterceptor(new FlowLoginInterceptor()).addPathPatterns("/**");
		//DoorduSessionStrategy.TOKEN_KEY = "_session";

        super.addInterceptors(registry);
	}

    @Bean(value = {"springSessionRedisTaskExecutor", "taskExector"})
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(coresize);
        executor.setMaxPoolSize(maxsize);
        executor.setQueueCapacity(queuesize);
        executor.setKeepAliveSeconds(keepAlived);
        return executor;
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize(1024L * 1024L*100L);
        return factory.createMultipartConfig();
    }
	//验证码相关代码
//	@Bean
//	public CaptchaServlet captchaServlet() {
//		return new CaptchaServlet();
//	}

//	@Bean
//	public ServletRegistrationBean testServletRegistrationBean(CaptchaServlet captchaServlet) {
//		ServletRegistrationBean registration = new ServletRegistrationBean(captchaServlet);
//		registration.setEnabled(true);
//		registration.addUrlMappings("/captcha.jpg");
//		return registration;
//	}

}
